<?php
namespace app\Http\Controllers\admin_system;

use App\Http\Controllers\Controller;
use App\Module\Message;
use App\PublicMethods;
use App\Module\EntManageuser;
use Illuminate\Http\Request;
use Cookie, Redirect, DB;

class MessageController extends Controller{
    public function index($keyword = '')
    {
        if ($keyword != '') {
            $message = Message::select('MessaID', 'States', 'ContactDetails', 'MessContent', 'DeleteMark', 'ReleaseDate')
            ->where('DeleteMark', '1')
            ->where('MessContent', 'like', '%' . $keyword . '%')
            ->orderBy('ReleaseDate', 'desc')
            ->paginate(20);
        } else {
            $message = Message::select('MessaID', 'States', 'ContactDetails', 'MessContent', 'DeleteMark', 'ReleaseDate')
            ->where('DeleteMark', '1')
            ->orderBy('ReleaseDate', 'desc')
            ->paginate(20);
        }
        return view('admin_system.message.index', compact('message'));
    }
    public function return_UserID($AName, $AKey)
    {
        $EntManageuser = EntManageuser::where('UserName', '=', $AName)->where('UserPwd', '=', md5($AKey))
        ->where('DeleteMark', '=', '1')
        ->first();
        return $EntManageuser['UserID'];
    }
    public function indexedit($id)
    {
          try {
          
            $message = Message::findOrFail($id);
        } catch (ModelNotFoundException $e) {
            throw new NotFoundHttpException();
        }
        return view('admin_system.message.indexEdit', compact('message'));
    }
    
    public function indexupdate(Request $request, $id)
    {
        $AName = $request->cookie('AName');
        $AKey = $request->cookie('AKey');
        $MasterID = $this->return_UserID($AName, $AKey);
        $message = Message::find($id);
        $message->AdminRemarks = $request->get('txtAdminRemarks');
        $message->MasterID = $MasterID;
        $message->ReleaseDate = $request->get('txtReleaseDate').date(' H:i:s',time());
        $message->save();
        $result = '';
        if ($message) {
            $result = '留言信息修改成功！';
        } else {
            $result = '留言信息修改失败！';
        }
        return redirect::back()->withInput()->withErrors($result);
    }
    
    public function indexdelete(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    Message::where('MessaID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    Message::whereIn('MessaID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }
}